<?php

declare(strict_types=1);

namespace App\Chat\Service;

use App\Chat\Cache\Repository\LockRedis;
use App\CustHub\Helpers\Robot;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChRoom;
use App\CustHub\Model\ChTalkSession;
use App\CustHub\Service\ChRoomSyncService;
use Carbon\Carbon;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;
use function Hyperf\Coroutine\co;

class TalkRoomService extends AbstractService
{
    #[Inject]
    protected TalkSessionService $talkSessionService;

    #[Inject]
    protected ChRobotMapper $robotMapper;

    public function create(array $params)
    {
        $robotId = (int)$params['robot_id'];
        $robotInfo = $this->robotMapper->findById($robotId);
        $useridList = json_decode($params['userid_list'],true);
        $robotApiService = make(\App\Common\Robot\Robot::class,[$robotInfo->server_id,$robotInfo->uuid])->gateway();

        $uid = $robotInfo->uid;
        $mainUid = $robotInfo->main_uid;
        $result = $robotApiService->createRoom($useridList);
        //群聊创建失败
        if($result === false){
            throw new NormalStatusException('群聊创建失败，请稍后再试');
        }
        //群微信ID
        $roomWxid = $result['room_id'];

        $roomDetailList = $robotApiService->getRoomDetail([$roomWxid]);
        $roomDetail = array_shift($roomDetailList);
        container()->get(ChRoomSyncService::class)->saveRoom($robotApiService,$roomDetail,$uid,$mainUid,$robotId);

        $result = $this->talkSessionService->create($mainUid,$robotId, $params['uid'], $roomWxid, 2);
        if (!$result) {
            throw new NormalStatusException('会话创建失败');
        }

        $data = ChTalkSession::item([
            'id'          => $result['id'],
            'talk_type'   => 2,
            'robot_id'    => $robotId,
            'receiver_id' => $roomWxid,
        ]);

        $groupInfo      = ChRoom::query()->where('room_wxid', $roomWxid)
            ->whereHas('robots',function ($query) use ($robotId) {
                $query->where('robot_id',$robotId);
            })
            ->first(['room_name', 'room_avatar_url']);
        $data['name']   = $groupInfo->room_name ?? '';
        $data['avatar'] = $groupInfo->room_avatar_url ?? '';
        $data['msg_text']   = '';
        $data['updated_at'] = Carbon::now();
        return $data;
    }


    public function invite(array $params): bool
    {
        $uid = $params['uid'];
        $robot = $this->robotMapper->findById($params['robot_id']);
        $userId = $params['user_id'];
        if(empty($robot) || $robot->login_status != 1){
            throw new NormalStatusException('请先登录企微号');
        }

        $api = make(\App\Common\Robot\Robot::class,[$robot->server_id,$robot->uuid])->gateway();

        $roomWxIdList = json_decode($params['room_wxid_list'],true);
        co(function () use ($api,$robot,$roomWxIdList,$userId,$uid){
            foreach ($roomWxIdList as $roomWxId){
                $api->inviteFriendToRoom($roomWxId,[$userId]);
                $this->talkSessionService->create($robot->main_uid,$robot->id, $uid, $roomWxId, 2);
            }
            Coroutine::sleep(rand(4,8));
        });
        return true;
    }
}